﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class MapManager : MonoBehaviour {

	static MapManager _instance;
	public static MapManager instance
	{
		get
		{
			return _instance;
		}
	}

	public int _minWidth = 3;
	public int _minHeight = 3;

	public int _maxWidth = 20;
	public int _maxHeight = 20;

	public GameObject _baseTilePrefab;

	public int _currentWidth = 8;
	public int _currentHeight = 11;

	public GameObject[,] _tiles;

    public TILESTYLE _editTileStyle = TILESTYLE.NORMAL;

	public List<Transform> _pathList = new List<Transform> ();
	// hit의 transform은 참조로 쓰이기 때문에 편하기 위해서 이걸 씀

	public string _fileName = "Map";

	void Awake()
	{
		_instance = this;

		LoadMapDataFromFile ();
	}

	public void CreatTiles(MapManager mapManager){
		int width = mapManager._currentWidth;
		int height = mapManager._currentHeight;

		mapManager._tiles = new GameObject[width, height];
		for(int i=0; i<width; i++){
			for(int j=0; j<height; j++){
				GameObject obj = (GameObject) Instantiate(mapManager._baseTilePrefab);
				obj.transform.parent = mapManager.transform;
				obj.transform.localPosition = new Vector3(i,0.0f,j);
				obj.name = i+"_"+j;
				mapManager._tiles[i,j] = obj;

				TileInfo tileInfo = mapManager._tiles[i, j].GetComponent<TileInfo>();

				tileInfo.UpdateMaterial();
			}
		}
	}

	public void RemoveAllTiles(){
		List<GameObject> gameObjectList = new List<GameObject>();
		foreach (Transform child in transform) {
			gameObjectList.Add(child.gameObject);
		}

		for(int i=0; i<gameObjectList.Count; i++){
			if(Application.isPlaying == true){
				Destroy(gameObjectList[i]);
				// for playing 
				// it will be delayed because of reference of itself
			}
			else{
				DestroyImmediate(gameObjectList[i]);
				// for editor
			}
		}

		gameObjectList.Clear ();
		gameObjectList = null;
		_tiles = null;

		_pathList.Clear ();
	}

	public Vector3 GetVector3FromString(string text)
	{
		string[] datas = text
			.Replace ('(', ' ')
			.Replace (')', ' ')
			.Split (',');

		float x = float.Parse (datas [0]);
		float y = float.Parse (datas [1]);
		float z = float.Parse (datas [2]);

		return new Vector3 (x, y, z);
	}

	public Transform[] GetPathArray()
	{
		return _pathList.ToArray ();
	}

	public void LoadMapDataFromFile()
	{
		RemoveAllTiles();
		
		string filePath = "MapData/" + _fileName;
		TextAsset asset = (TextAsset)Resources.Load (filePath, typeof(TextAsset));
		
		if (asset == null)
		{
			Debug.Log("Can not open file on Assets/" + filePath + ".txt");
			return;
		}
		
		Stream stream = new MemoryStream(asset.bytes);
		TextReader textReader = new StreamReader(stream);
		
		// read width
		string text = textReader.ReadLine ();
		string widthText = text.Substring (text.IndexOf (' ') + 1);
		_currentWidth = int.Parse (widthText);
		
		//read height
		 text = textReader.ReadLine ();
		string heightText = text.Substring (text.IndexOf (' ') + 1);
		_currentHeight = int.Parse (heightText);

		//create map
		_tiles = new GameObject[_currentWidth, _currentHeight];
		for (int i = 0; i < _currentWidth; i++)
		{
			for (int j = 0; j < _currentHeight; j++)
			{
				text = textReader.ReadLine ();
				string[] infos = text.Split ('\t');

				GameObject obj = Instantiate(_baseTilePrefab) as GameObject;
				obj.name = i + "_" + j;
				obj.transform.parent = transform;
				obj.transform.position = GetVector3FromString(infos[0]);
				obj.transform.eulerAngles = GetVector3FromString(infos[1]);

				TileInfo tileInfo = obj.GetComponent<TileInfo>();
				tileInfo.currentTileStyle = (TILESTYLE)(int.Parse(infos[2]));
				tileInfo.UpdateMaterial();

				_tiles[i, j] = obj;
			}
		}

		//load path
		text = textReader.ReadLine ();
		string pathCountText = text.Substring (text.IndexOf (' '));
		int pathCount = int.Parse (pathCountText);
		for (int i = 0; i < pathCount; i++)
		{
			text = textReader.ReadLine();

			string[] tiles = text.Split('\t');

			int x = int.Parse(tiles[0]);
			int y = int.Parse(tiles[1]);

			_pathList.Add (_tiles[x, y].transform);
		}
	} // End of LoadMapDataFromFile()
}






























